package bean.managed;

import entity.ContactEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.ContactEntityFacade;

import entity.SystemUserEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import managedbean.AbstractBacking;
import org.primefaces.model.DualListModel;
import util.PasswordEncryptor;

@ManagedBean(name = "contactEntityController")
@SessionScoped
public class ContactEntityController extends AbstractBacking implements Serializable {

    private ContactEntity current;
    private DataModel items = null;
    @EJB
    private bean.session.ContactEntityFacade ejbFacade;
    @EJB
    private bean.session.PersonEntityFacade personFacade;
    @EJB
    private bean.session.UserSettingEntityFacade settingFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private DualListModel<String> addressBook;
    private DualListModel<String> addressBookCc;
    private String newPassword;
    private String oldPassword;

    public ContactEntityController() {
    }

    public ContactEntity getSelected() {
        if (current == null) {
            current = new ContactEntity();
            selectedItemIndex = -1;
        }
        return current;
    }

    public ContactEntity getCurrent() {
        return current;
    }

    public void setCurrent(ContactEntity current) {
        this.current = current;
    }

    private ContactEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (ContactEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "/entities/contactEntity/ViewContact";
    }

    public void setupCurrent(ContactEntity contact) {
        current = contact;
//        System.out.println("contact current is set to " + contact.getPerson().getName());
        selectedItemIndex = -1;
    }

    public String viewAccount() {
        current = getLoginPerson().getContact();
        System.out.println("Contact View: " + current);
        return "/entities/contactEntity/ViewContact?faces-redirect=true";
    }

    public String prepareCreate() {
        current = new ContactEntity();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            current.created(getLoginPerson());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ContactEntityCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (ContactEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ContactEntityUpdated"));
            return "ViewContact";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (ContactEntity) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            current.modified(getLoginPerson());
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ContactEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public void validateEmail(FacesContext context, UIComponent validate, Object value) {

        String inputEmail = (String) value;
        if (ejbFacade.checkEmailExist(inputEmail)) {
            FacesMessage message = new FacesMessage();
            message.setDetail("Email address exists");
            message.setSummary("Email address exists");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message);
        }
    }

    public void setAddressBook(DualListModel<String> addressBook) {
        this.addressBook = addressBook;
    }

    public void setAddressBookCc(DualListModel<String> addressBookCc) {
        this.addressBookCc = addressBookCc;
    }

    @FacesConverter(forClass = ContactEntity.class)
    public static class ContactEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ContactEntityController controller = (ContactEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "contactEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof ContactEntity) {
                ContactEntity o = (ContactEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ContactEntityController.class.getName());
            }
        }
    }

//    public DualListModel<ContactEntity> getAddressBook() {
//        addressBook = getFacade().getAllEmailAdd();
//        return addressBook;
//    }
    public DualListModel<String> getAddressBook() {
        if (addressBook == null) {
            List<String> source = new ArrayList<String>();
            List<String> target = new ArrayList<String>();
            ArrayList<ContactEntity> contact = getFacade().getAllContact();
            for (int i = 0; i < contact.size(); i++) {
                source.add(contact.get(i).getEmail());
            }
            addressBook = new DualListModel<String>(source, target);
        }
        return addressBook;
    }

    public DualListModel<String> getAddressBookCc() {
        if (addressBookCc == null) {
            List<String> source = new ArrayList<String>();
            List<String> target = new ArrayList<String>();
            ArrayList<ContactEntity> contact = getFacade().getAllContact();
            for (int i = 0; i < contact.size(); i++) {
                source.add(contact.get(i).getEmail());
            }
            addressBookCc = new DualListModel<String>(source, target);
        }
        return addressBookCc;
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }

    public String changePassword() {
        String encryptedOldInDb = current.getPerson().getPassword();
        boolean correctPass = PasswordEncryptor.checkPassword(oldPassword, encryptedOldInDb);
        if (correctPass) {
            current.getPerson().setPassword(PasswordEncryptor.encryptPassword(newPassword));
            JsfUtil.addSuccessMessage("Password changed successfully");
            current.modified(getLoginPerson());
            personFacade.edit(current.getPerson());
        } else {
            JsfUtil.addErrorMessage("Wrong old password entered");
        }
        oldPassword = null;
        newPassword = null;

        return "ViewContact";
    }

    public boolean isIndeedSystemUser() {
        return (current.getPerson() instanceof SystemUserEntity);
    }

    public SystemUserEntity getSystemUser() {
        if (isIndeedSystemUser()) {
            return ((SystemUserEntity) current.getPerson());
        } else {
            return null;
        }
    }

    public void editSetting() {
        SystemUserEntity user = getSystemUser();
        if (user != null) {
            settingFacade.edit(user.getSetting());
        }
    }
}
